package com.cctc.mychat.common.protocol.codec;

import com.cctc.mychat.common.protocol.message.MessageVersion;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class UnpacketDecoder extends LengthFieldBasedFrameDecoder {
    public static final int LENGTH_FIELD_OFFSET = 4 + 1 + 1 + 1;
    private static final int LENGTH_FIELD_LENGTH = 4;

    public UnpacketDecoder() {
        super(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = (ByteBuf) super.decode(ctx, in);
        if (frame != null) {
            int flag = frame.getInt(frame.readerIndex());
            if (flag != MessageVersion.MAGIC) return null;
        }
        return frame;
    }
}
